from google.appengine.api import xmpp

from md5crypt import md5crypt
from itertools import product

def brutecrack(pg, the_hash):
    magic, salt = the_hash[1:].split('$')[:2]
    magic = '$' + magic + '$'
    for pwd in pg:
        if md5crypt(pwd, salt, magic) == the_hash:
            return pwd
    else:
        return ''

def getchars(pattern='0.Aa'):
    allx = []
    if '.' in pattern:
        allx.extend(range(32,48))
        allx.extend(range(58,65))
        allx.extend(range(91,97))
        allx.extend(range(123,127))
    if '0' in pattern:
        allx.extend(range(48,58))
    if 'A' in pattern:
        allx.extend(range(65,91))
    if 'a' in pattern:
        allx.extend(range(97,123))

    return [chr(x) for x in allx]

def pwdgen(pattern='0.Aa', minl=3, maxl=12, prefix=''):
    chars = getchars(pattern)

    for l in range(minl, maxl+1):
        for pw in product(chars, repeat=l):
            yield prefix + ''.join(pw)

def crackProc(sender ,cmd):
    thehash = '$apr1$Sv79Q.N6$gDvVSOADOe8Pju3cZ.umy/' #md5crypt('zbcz', 'J.w5a/..', '$apr1$')
    pg = pwdgen('a0', minl=4, maxl=5, prefix='jxd')
    pwd = brutecrack(pg, thehash)
    xmpp.send_message(sender,pwd if pwd else 'soryy')

